package com.etc;

import org.junit.Before;
import org.junit.Test;

import java.sql.*;

public class PhoenixTest {

    Connection connection = null;
    String sql = "";
    PreparedStatement ps = null;
    ResultSet rs = null;

    @Before
    public void init() throws ClassNotFoundException, SQLException {
        //连接驱动
        Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
        //获得到连接对象
        connection = DriverManager.getConnection("jdbc:phoenix:master:2181");
    }
//查询
@Test
public void query() throws SQLException {
    sql = "select * from person";
    //根据连接对象获得发送器
    ps = connection.prepareStatement(sql);
    rs = ps.executeQuery();
    while (rs.next()) {
        System.out.println(rs.getString("NAME"));
    }

    ps.close();
    connection.close();
}
//创建表
@Test
public void createTable() throws SQLException {
    sql = "create table if not exists t_person(id integer not null primary key,name varchar(20),age integer)";
    ps = connection.prepareStatement(sql);
    ps.execute();
    System.out.println("runnning:"+sql);
    ps.close();
    connection.close();
}
//添加数据
@Test
public void add() throws SQLException {
    sql = "upsert into t_person select * from users where age > 13";
    ps = connection.prepareStatement(sql);
    int i = ps.executeUpdate();
    connection.commit();
    System.out.println("running:"+i+"行");
    ps.close();
    connection.close();
}
//删除数据
@Test
public void delete() throws SQLException {
    sql = "delete from t_person where age=16";
    ps = connection.prepareStatement(sql);
    int i = ps.executeUpdate();
    connection.commit();
    System.out.println("running:"+i+"行");
    ps.close();
    connection.close();
}
//更新数据
@Test
public void update() throws SQLException {
    sql = "upsert into t_person (id,name) values (?,?)";
    ps = connection.prepareStatement(sql);

    ps.setInt(1,1);
    ps.setString(2,"up");

    int i = ps.executeUpdate();
    connection.commit();
    System.out.println("running:"+i+"行");
    ps.close();
    connection.close();
}
    }

